package com.draw.cli.gui;

import javax.swing.JProgressBar;

public class MemoryBar extends JProgressBar implements Runnable {
	private static final long serialVersionUID = -5395921520637886472L;

	private static final long DELTA = 100;
	private static final MemoryBar instance = new MemoryBar();
	
	private boolean running ;

	public static MemoryBar getInstance() {
		return instance;
	}

	private MemoryBar() {
		super(JProgressBar.HORIZONTAL);
		this.running = false;
		this.setMaximum(100);
		this.setMinimum(0);
		this.setStringPainted(true);
	}

	private void refresh() {
		long max = Runtime.getRuntime().totalMemory();
		long free = Runtime.getRuntime().freeMemory();
		int val = (int)((free*100)/max);
		this.setValue(val);
	}
	
	public void start () {
		if ( ! this.running ) {
			this.running = true;
			Thread th = new Thread(this);
			th.start();
		}
	}
	
	public void stop () {
		this.running = false;
	}

	@Override
	public void run() {
		while (this.running) {
			refresh();
			try {
				Thread.sleep(DELTA);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
			}
		}
	}

}
